package com.Interceptor;

import com.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 自定义拦截器
 * Created by yangziqiang on 16-9-19.
 */
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired private   RedisUtil redisutils;

    //执行前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        HandlerMethod handler=(HandlerMethod) o;
        HttpSession session = request.getSession();
        FailInterceptor methodAnnotation = handler.getMethodAnnotation(FailInterceptor.class);
        if (methodAnnotation!=null){
            return true;
        }else {
            String id = session.getId();
            ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            redisutils = (RedisUtil) ac1.getBean("redisutils");
            Object o1 = redisutils.get(id);
            if (o1 != null) {
                return true;
            }
            response.sendRedirect("/index/login");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {


        //System.out.println("2");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
       // System.out.println("3");
    }
}
